import Taro, { getCurrentPages } from '@tarojs/taro'
import {
  call, put, all, takeLatest, select
} from 'redux-saga/effects'
import api from '@API'
import {
  GET_TEMPLATE_AND_PACKS,
  GET_TEMPLATE_OPTIONS_DETAIL,
  GET_SERVICE_PACK_DETAIL,
  SET_SELECT_PATIENT,
  SET_SERVICE_PACK,
  SET_SELECT_DOCTOR,
  UPDATE_START_SURVEY,
  GET_ORDER_PACKS
} from '@ACTIONS/servicePack'
import { DEFAULT_TAKE } from '@CONSTANTS/common'
import Navigate from '@NAVIGATION/navigateManager'
import { isAndroid, getPlatform } from '@UTILS/common'
import { getTemplateList, getUser, getOrderPacksList } from './dataSelect'

const getTemplatesAndPacks = function* getTemplatesAndPacks(action) {
  try {
    const { payload: { skip } = {} } = action
    const preList = yield select(getTemplateList)
    const realSkip = skip === 0 ? 0 : preList.length
    const { Templates } = yield call(api.getTemplatesAndPacks, { skip: realSkip, take: DEFAULT_TAKE })

    yield put({
      type: GET_TEMPLATE_AND_PACKS.SUCCESS,
      data: skip === 0 ? Templates : [...preList, ...Templates],
      canLoadMore: Templates.length >= DEFAULT_TAKE
    })
  } catch (error) {
    yield put({ type: GET_TEMPLATE_AND_PACKS.FAILURE })
  }
}

const getTemplateById = function* getTemplateById(action) {
  try {
    const { payload } = action
    const { tId, isAsync } = payload || {}

    const { Template } = yield call(api.getTemplateOptionsDetail, { tId })
    yield put({ type: GET_TEMPLATE_OPTIONS_DETAIL.SUCCESS, data: Template, isAsync })
  } catch (error) {
    yield put({ type: GET_TEMPLATE_OPTIONS_DETAIL.FAILURE, error })
  }
}

const getServicePackDetail = function* getServicePackDetail(action) {
  try {
    const { payload } = action
    const { ServicePack } = yield call(api.getServicePackDetail, payload)
    yield put({ type: GET_SERVICE_PACK_DETAIL.SUCCESS, data: ServicePack })
  } catch (error) {
    yield put({ type: GET_SERVICE_PACK_DETAIL.FAILURE, error })
  }
}

const setSelectPatient = function* setSelectPatient(action) {
  try {
    const { payload: { patient, pId } = {} } = action
    const {
      p8Id, PatientId, Name, Birthdate, Gender
    } = patient || {}
    const payload = {
      PackId: pId,
      Patients: [{
        PatientId: p8Id || PatientId,
        Name,
        Birthdate,
        Gender
      }]
    }
    const { ServicePack } = yield call(api.selectPatients, payload)
    yield put({ type: SET_SERVICE_PACK.REQUEST, data: ServicePack })
  } catch (error) {
    yield put({ type: SET_SELECT_PATIENT.FAILURE, error })
  }
}

const setSelectDoctor = function* setSelectDoctor(action) {
  try {
    const { payload } = action
    const { ServicePack } = yield call(api.selectDoctor, payload)
    const { PackId } = ServicePack
    yield put({ type: SET_SERVICE_PACK.REQUEST, data: ServicePack })
    const user = yield select(getUser)

    Taro.showToast({
      title: '开启成功',
      icon: 'success',
      duration: 1000,
      mask: true,
      success: async () => {
        const delay = isAndroid() ? 0 : getCurrentPages().length * 150
        const { isWeb } = getPlatform()
        if (isWeb && Array.isArray(user?.ExternalIds) && user?.ExternalIds.length > 0) {
          Navigate.navigateBack(1)
          Navigate.redirectTo('myServiceRights', { pId: PackId })
          return
        }
        await Navigate.switchTab('myPage')
        setTimeout(() => {
          Navigate.myServiceRights({ pId: PackId })
        }, Math.min(delay, 1000))
      }
    })
  } catch (error) {
    yield put({ type: SET_SELECT_DOCTOR.FAILURE })
  }
}

const updatePackSurvey = function* updatePackSurvey(action) {
  try {
    const { payload } = action
    const { ServicePack } = yield call(api.updatePackSurvey, payload)
    yield put({ type: SET_SERVICE_PACK.REQUEST, data: ServicePack })
  } catch (error) {
    yield put({ type: UPDATE_START_SURVEY.FAILURE, error })
  }
}

const getOrderPacks = function* getOrderPacks(action) {
  try {
    const { payload: { skip } = {} } = action
    const preList = yield select(getOrderPacksList)
    const realSkip = skip === 0 ? 0 : preList.length
    const result = yield call(api.getMyServicePacks, { skip: realSkip, take: DEFAULT_TAKE })

    yield put({
      type: GET_ORDER_PACKS.SUCCESS,
      data: skip === 0 ? result : [...preList, ...result],
      canLoadMore: result.length >= DEFAULT_TAKE
    })
  } catch (error) {
    yield put({ type: GET_ORDER_PACKS.FAILURE })
  }
}

export default function* rootSaga() {
  yield all([
    takeLatest(GET_TEMPLATE_AND_PACKS.REQUEST, getTemplatesAndPacks),
    takeLatest(GET_TEMPLATE_OPTIONS_DETAIL.REQUEST, getTemplateById),
    takeLatest(GET_SERVICE_PACK_DETAIL.REQUEST, getServicePackDetail),
    takeLatest(SET_SELECT_PATIENT.REQUEST, setSelectPatient),
    takeLatest(SET_SELECT_DOCTOR.REQUEST, setSelectDoctor),
    takeLatest(UPDATE_START_SURVEY.REQUEST, updatePackSurvey),
    takeLatest(GET_ORDER_PACKS.REQUEST, getOrderPacks),
  ]);
}
